
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>JavaScript模块化 --- Commonjs、AMD、CMD、ES6 modules - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,前言随着前端js代码复杂度的提高，JavaScript模块化这个概念便被提出来，前端社区也不断地实现前端模块化，直到es6对其进行了规范，下面就介绍JavaScript模块化。
JavaScript,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">JavaScript模块化 --- Commonjs、AMD、CMD、ES6 modules</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                July 25, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/07/25/study/JavaScript%E6%A8%A1%E5%9D%97%E5%8C%96-Commonjs%E3%80%81AMD%E3%80%81CMD%E3%80%81ES6-modules/" title="JavaScript模块化 --- Commonjs、AMD、CMD、ES6 modules" class="">JavaScript模块化 --- Commonjs、AMD、CMD、ES6 modules</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    22k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    20 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/%E6%A8%A1%E5%9D%97%E5%8C%96/" rel="tag">模块化</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>随着前端js代码复杂度的提高，<code>JavaScript模块化</code>这个概念便被提出来，前端社区也不断地实现前端模块化，直到es6对其进行了规范，下面就介绍JavaScript模块化。</p>
<p><code>JavaScript模块化</code>是如何一步一步地发展起来的，并且也会主要对这些模块化方式做一个简单的比较。</p>
<h2 id="第一阶段：无模块化"><a href="#第一阶段：无模块化" class="headerlink" title="第一阶段：无模块化"></a>第一阶段：无模块化</h2><p>JavaScript最初的作用仅仅是验证表单，后来会添加一些动画，但是这些js代码很多在一个文件中就可以完成了，所以，我们只需要在html文件中添加一个<code>script</code>标签。</p>
<p>后来，随着前端复杂度提高，为了能够提高项目代码的可读性、可扩展性等，我们的js文件逐渐多了起来，不再是一个js文件就可以解决的了，而是把每一个js文件当做一个模块。那么，这时的js引入方式是怎样的呢？大概是下面这样：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"jquery.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span> 　</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"jquery_scroller.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"main.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"other1.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span> 　</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"other2.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"other3.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>即简单的将所有的js文件统统放在一起。但是这些文件的顺序还不能出错，比如jquery需要先引入，才能引入jquery插件，才能在其他的文件中使用jquery。</p>
<ul>
<li>优点</li>
</ul>
<p>相比于使用一个js文件，这种多个js文件实现最简单的模块化的思想是进步的</p>
<ul>
<li>缺点</li>
</ul>
<p><strong>污染全局作用域</strong>。 因为每一个模块都是暴露在全局的，简单的使用，会导致全局变量命名冲突，当然，我们也可以使用命名空间的方式来解决。对于大型项目，各种js很多，开发人员必须手动解决模块和代码库的依赖关系，后期维护成本较高。<br><strong>依赖关系不明显，不利于维护</strong>。 比如main.js需要使用jquery，但是，从上面的文件中，我们是看不出来的，如果jquery忘记了，那么就会报错。</p>
<a id="more"></a>
<h2 id="第二阶段：-CommonJS规范"><a href="#第二阶段：-CommonJS规范" class="headerlink" title="第二阶段： CommonJS规范"></a>第二阶段： CommonJS规范</h2><p><code>CommonJS</code>就是一个<code>JavaScript模块化</code>的规范，该规范最初是用在服务器端的<code>node</code>的，前端的<code>webpack</code>也是对CommonJS原生支持的。</p>
<p>根据这个规范，<em>每一个文件就是一个模块</em>，其内部定义的变量是属于这个模块的，不会对外暴露，也就是说不会污染全局变量。</p>
<p>CommonJS的核心思想就是通过 <strong>require 方法来同步加载所要依赖的其他模块，然后通过 exports 或者 module.exports 来导出需要暴露的接口</strong>。如下所示</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// a.js</span></span><br><span class="line"><span class="keyword">var</span> x = <span class="number">5</span>; <span class="keyword">var</span> addX = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123; <span class="keyword">return</span> value + x; &#125;; <span class="built_in">module</span>.exports.x = x; <span class="built_in">module</span>.exports.addX = addX;</span><br></pre></td></tr></table></figure>
<p>这里的<code>a.js</code>就是一个<code>CommonJS</code>规范的模块了。 这里的<code>module</code>就代表了这个模块，<code>module</code>的<code>exports</code>属性就是对外暴露的接口，可以对外导出外部可以访问的变量，比如这里的x和addX。</p>
<p>exports 是对 module.exports 的引用。比如我们可以认为在一个模块的<strong>顶部</strong>有这句代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> = <span class="keyword">export</span>.Module;</span><br></pre></td></tr></table></figure>
<p>所以，我们不能直接给exports赋值，比如<code>number、function</code>等。</p>
<p>然后我们就可以在其他模块中引入这个模块使用了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="built_in">require</span>(<span class="string">'./a.js'</span>);</span><br><span class="line"> <span class="built_in">console</span>.log(example.x); <span class="comment">// 5</span></span><br><span class="line"> <span class="built_in">console</span>.log(example.addX(<span class="number">1</span>)); <span class="comment">// 6</span></span><br></pre></td></tr></table></figure>
<p>这里的require就会获取到a.js所暴露的module.exports变量，然后就可以使用其暴露的x和addX了。</p>
<ul>
<li>优点：</li>
</ul>
<p>CommonJS规范在服务器端率先完成了JavaScript的模块化，<strong>解决了依赖、全局变量污染的问题</strong>，这也是js运行在服务器端的必要条件。</p>
<ul>
<li>缺点：</li>
</ul>
<p>此文主要是浏览器端js的模块化， 由于 CommonJS 是<code>同步加载模块</code>的，在服务器端，文件都是保存在硬盘上，所以同步加载没有问题，但是对于浏览器端，需要将文件从服务器端请求过来，那么同步加载就不适用了，所以，CommonJS是不适用于浏览器端的。</p>
<h2 id="第三阶段：-AMD规范"><a href="#第三阶段：-AMD规范" class="headerlink" title="第三阶段： AMD规范"></a>第三阶段： AMD规范</h2><p>之前提到: CommonJS规范加载模块是<code>同步</code>的，也就是说，只有加载完成，才能执行后面的操作。AMD规范则是<code>非同步</code>加载模块，允许指定回调函数。由于Node.js主要用于服务器编程，模块文件一般都已经存在于本地硬盘，所以加载起来比较快，不用考虑非同步加载的方式，所以CommonJS规范比较适用。但是，如果是浏览器环境，要从服务器端加载模块，这时就必须采用非同步模式，因此浏览器端一般采用AMD规范。而AMD规范的实现，就是大名鼎鼎的<code>require.js</code>了</p>
<p>AMD标准中，定义了下面两个API：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span><span class="built_in">require</span>([<span class="built_in">module</span>], callback)</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>define(id, [depends], callback)</span><br></pre></td></tr></table></figure>
<p>即通过define来定义一个模块，然后使用require来加载一个模块。 并且，require还支持CommonJS的模块导出方式。</p>
<p>定义alert模块：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">define(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> alertName = <span class="function"><span class="keyword">function</span> (<span class="params">str</span>) </span>&#123;</span><br><span class="line">      alert(<span class="string">"I am "</span> + str);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> alertAge = <span class="function"><span class="keyword">function</span> (<span class="params">num</span>) </span>&#123;</span><br><span class="line">      alert(<span class="string">"I am "</span> + num + <span class="string">" years old"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      alertName: alertName,</span><br><span class="line">      alertAge: alertAge</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;);</span><br><span class="line"><span class="string">``</span><span class="string">`  </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">引入模块：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>js</span><br><span class="line"><span class="built_in">require</span>([<span class="string">'alert'</span>], <span class="function"><span class="keyword">function</span> (<span class="params">alert</span>) </span>&#123;</span><br><span class="line">  alert.alertName(<span class="string">'JohnZhu'</span>);</span><br><span class="line">  alert.alertAge(<span class="number">21</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>但是，在使用require.js的时候，我们必须要 <strong>提前加载所有的依赖，然后才可以使用，而不是需要使用时再加载</strong>。</p>
<ul>
<li>优点：</li>
</ul>
<p>适合在浏览器环境中异步加载模块。可以并行加载多个模块。</p>
<ul>
<li>缺点：</li>
</ul>
<p>提高了开发成本，并且不能按需加载，而是必须提前加载所有的依赖。</p>
<h2 id="第四阶段：CMD规范"><a href="#第四阶段：CMD规范" class="headerlink" title="第四阶段：CMD规范"></a>第四阶段：CMD规范</h2><p>CMD规范是阿里的玉伯提出来的，实现js库为sea.js。 它和requirejs非常类似，即一个js文件就是一个模块，但是CMD的加载方式更加优秀，是<code>通过按需加载</code>的方式，而不是必须在模块开始就加载所有的依赖。如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">define(<span class="function"><span class="keyword">function</span>(<span class="params">require, exports, module</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> $ = <span class="built_in">require</span>(<span class="string">'jquery'</span>);</span><br><span class="line">    <span class="keyword">var</span> Spinning = <span class="built_in">require</span>(<span class="string">'./spinning'</span>);</span><br><span class="line">    exports.doSomething = ...</span><br><span class="line">    <span class="built_in">module</span>.exports = ...</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ul>
<li>优点：</li>
</ul>
<p>同样实现了浏览器端的模块化加载。<br>可以按需加载，依赖就近。</p>
<ul>
<li>缺点：</li>
</ul>
<p>依赖SPM打包，模块的加载逻辑偏重。</p>
<p>其实，这时我们就可以看出 <strong>AMD和CMD的区别</strong>了，<em>前者是对于依赖的模块提前执行，而后者是延迟执行。 前者推崇依赖前置，而后者推崇依赖就近</em>，即只在需要用到某个模块的时候再require。 如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// AMD</span></span><br><span class="line"> define([<span class="string">'./a'</span>, <span class="string">'./b'</span>], <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 依赖必须一开始就写好</span></span><br><span class="line">    a.doSomething()</span><br><span class="line">    <span class="comment">// 此处略去 100 行</span></span><br><span class="line">    b.doSomething()</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// CMD</span></span><br><span class="line">define(<span class="function"><span class="keyword">function</span>(<span class="params">require, exports, module</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="built_in">require</span>(<span class="string">'./a'</span>)</span><br><span class="line">    a.doSomething()</span><br><span class="line">    <span class="comment">//此处略去100行</span></span><br><span class="line">    varb=<span class="built_in">require</span>(<span class="string">'./b'</span>)</span><br><span class="line">    <span class="comment">//依赖可以就近书写</span></span><br><span class="line">    b.doSomething()</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="第五阶段：-ES6模块化"><a href="#第五阶段：-ES6模块化" class="headerlink" title="第五阶段： ES6模块化"></a>第五阶段： ES6模块化</h2><p>之前的几种模块化方案都是前端社区自己实现的，只是得到了大家的认可和广泛使用，而ES6的模块化方案是真正的规范。 在ES6中，我们可以使用 <code>import</code> 关键字引入模块，通过 <code>export</code> 关键字导出模块，功能较之于前几个方案更为强大，也是我们所推崇的.</p>
<p>但是由于ES6目前无法在浏览器中执行，所以，我们只能通过<code>babel</code>将不被支持的<code>import</code>编译为当前受到广泛支持的 <code>require</code>。</p>
<p>虽然目前import和require的区别不大，但是还是推荐使用使用es6，因为未来es6必定是主流，对于代码的迁移成本还是非常容易的。 如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">'../store/index'</span></span><br><span class="line"><span class="keyword">import</span> &#123;mapState, mapMutations, mapActions&#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">'../assets/js/request'</span></span><br><span class="line"><span class="keyword">import</span> util <span class="keyword">from</span> <span class="string">'../utils/js/util.js'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    created () &#123;</span><br><span class="line">    <span class="keyword">this</span>.getClassify();</span><br><span class="line">    <span class="keyword">this</span>.RESET_VALUE();</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'created'</span> ,<span class="keyword">new</span> <span class="built_in">Date</span>().getTime());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="第六阶段：-UMD"><a href="#第六阶段：-UMD" class="headerlink" title="第六阶段： UMD"></a>第六阶段： UMD</h2><p>通过一层自执行函数来兼容各种模块化规范的写法，兼容 AMD / CMD / CommonJS 等模块化规范，贴上代码胜过千言万语，需要特别注意的是 ES Module 由于会对静态代码进行分析，故这种运行时的方案无法使用，此时通过 CommonJS 进行兼容；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span> (<span class="params">global, factory</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> exports === <span class="string">'object'</span>) &#123;</span><br><span class="line">    <span class="built_in">module</span>.exports = factory();</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> define === <span class="string">'function'</span> &amp;&amp; define.amd) &#123;</span><br><span class="line">    define(factory);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">this</span>.eventUtil = factory();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)(<span class="keyword">this</span>, <span class="function"><span class="keyword">function</span> (<span class="params">exports</span>) </span>&#123;</span><br><span class="line"> ​ <span class="comment">// Define Module</span></span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(exports, <span class="string">"__esModule"</span>, &#123;</span><br><span class="line">    value: <span class="literal">true</span></span><br><span class="line">  &#125;);</span><br><span class="line">  exports.default = <span class="number">42</span>;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="构建工具中的实现"><a href="#构建工具中的实现" class="headerlink" title="构建工具中的实现"></a>构建工具中的实现</h2><p>为了模块化在浏览器中实现，我们可以借助一些模块化打包工具进行打包(以webpack为例)，定义了项目入口之后，会先快速地进行依赖的分析，然后将所有依赖的模块转换成浏览器兼容的对应模块化规范的实现；</p>
<h3 id="模块化的基础"><a href="#模块化的基础" class="headerlink" title="模块化的基础"></a>模块化的基础</h3><p>从上面的介绍中，我们已经对其规范和实现有了一定的了解；在浏览器中，要实现 CommonJS 规范，只需要实现 module / exports / require / global 这几个属性，由于浏览器中是无法访问文件系统的，因此 require 过程中的文件定位需要改造为加载对应的 JS 片段（webpack 采用的方式为通过函数传参实现依赖的引入）。</p>
<p>下面为webpack打包出来的代码快照如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span> (<span class="params">modules</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// The module cache</span></span><br><span class="line">  <span class="keyword">var</span> installedModules = &#123;&#125;;</span><br><span class="line">  <span class="comment">// The require function</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">__webpack_require__</span>(<span class="params">moduleId</span>) </span>&#123;&#125;</span><br><span class="line">  <span class="keyword">return</span> __webpack_require__(<span class="number">0</span>); <span class="comment">// ---&gt; 0</span></span><br><span class="line">&#125;)</span><br><span class="line">(&#123;</span><br><span class="line">  <span class="number">0</span>: <span class="function"><span class="keyword">function</span> (<span class="params">module, exports, __webpack_require__</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// Define module A</span></span><br><span class="line">    <span class="keyword">var</span> moduleB = __webpack_require__(<span class="number">1</span>); <span class="comment">// ---&gt; 1</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="number">1</span>: <span class="function"><span class="keyword">function</span> (<span class="params">module, exports, __webpack_require__</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// Define module B</span></span><br><span class="line">    exports = &#123;&#125;; <span class="comment">// ---&gt; 2</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>实际上，ES Module 的处理同 CommonJS 相差无几，只是在定义模块和引入模块时会去处理 __esModule 标识，从而兼容其在语法上的差异。</p>
<h3 id="异步和扩展"><a href="#异步和扩展" class="headerlink" title="异步和扩展"></a>异步和扩展</h3><p>1、浏览器环境下，网络资源受到较大的限制，因此打包出来的文件如果体积巨大，对页面性能的损耗极大，因此需要对构建的目标文件进行拆分，同时模块也需要支持动态加载；</p>
<p>webpack 提供了两个方法 <code>require.ensure()</code> 和 <code>import()</code> （推荐使用）进行模块的动态加载，至于其中的原理，跟上面提及的 AMD &amp; CMD 所见略同，import() 执行后返回一个 Promise 对象，其中所做的工作无非也是动态新增 script 标签，然后通过 <code>onload / onerror</code> 事件进一步处理。</p>
<p>2、由于 require 函数是完全自定义的，我们可以在模块化中实现更多的特性，比如通过修改 require.resolve 或 Module._extensions 扩展支持的文件类型，使得 css / .jsx / .vue / 图片等文件也能为模块化所使用；</p>
<h2 id="附录一：特性一览表"><a href="#附录一：特性一览表" class="headerlink" title="附录一：特性一览表"></a>附录一：特性一览表</h2><table>
<thead>
<tr>
<th>模块化规范</th>
<th style="text-align:right">加载方式</th>
<th style="text-align:right">加载时机</th>
<th style="text-align:right">运行环境</th>
<th style="text-align:right">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>AMD</td>
<td style="text-align:right">异步</td>
<td style="text-align:right">运行时</td>
<td style="text-align:right">浏览器</td>
<td style="text-align:right"></td>
</tr>
<tr>
<td>CMD</td>
<td style="text-align:right">异步</td>
<td style="text-align:right">运行时</td>
<td style="text-align:right">浏览器</td>
<td style="text-align:right"></td>
</tr>
<tr>
<td>CommonJS</td>
<td style="text-align:right">同步/异步</td>
<td style="text-align:right">运行时</td>
<td style="text-align:right">浏览器/node</td>
<td style="text-align:right"></td>
</tr>
<tr>
<td>ES Module</td>
<td style="text-align:right">同步/异步</td>
<td style="text-align:right">编译阶段</td>
<td style="text-align:right">浏览器/node</td>
</tr>
</tbody>
</table>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#第一阶段：无模块化"><span class="toc-number">1.1.</span> <span class="toc-text">第一阶段：无模块化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第二阶段：-CommonJS规范"><span class="toc-number">1.2.</span> <span class="toc-text">第二阶段： CommonJS规范</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第三阶段：-AMD规范"><span class="toc-number">1.3.</span> <span class="toc-text">第三阶段： AMD规范</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第四阶段：CMD规范"><span class="toc-number">1.4.</span> <span class="toc-text">第四阶段：CMD规范</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第五阶段：-ES6模块化"><span class="toc-number">1.5.</span> <span class="toc-text">第五阶段： ES6模块化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第六阶段：-UMD"><span class="toc-number">1.6.</span> <span class="toc-text">第六阶段： UMD</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#构建工具中的实现"><span class="toc-number">1.7.</span> <span class="toc-text">构建工具中的实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#模块化的基础"><span class="toc-number">1.7.1.</span> <span class="toc-text">模块化的基础</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#异步和扩展"><span class="toc-number">1.7.2.</span> <span class="toc-text">异步和扩展</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#附录一：特性一览表"><span class="toc-number">1.8.</span> <span class="toc-text">附录一：特性一览表</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
